package com.irdstudio.efp.esb.api.rest.sed.apply;


import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.constant.SDicToExternalConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TraceUtil;
import com.irdstudio.basic.framework.core.util.sdic.SDicToExternal;
import com.irdstudio.basic.framework.web.controller.AbstractController;
import com.irdstudio.efp.esb.api.bean.sed.yx.ReqPersonLetterAppBean;
import com.irdstudio.efp.esb.api.bean.sed.yx.RespNlsApplArr;
import com.irdstudio.efp.esb.api.bean.sed.yx.RespPersonLetterAppBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.sed.LetterQueryType;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
* 普税贷产品对税e贷产品的此部分代码做了复用
* 说明：为了保证功能的复用性、提升开发的工作效率，对该代码进行了复用
* 评估是否会影响线上功能：否
* 评估时间：2020/5/25
* 处理方案：保留复用
*/
/**
 * 需求编号：【2019D0519】（业务提的需求编号）
 * 问题编号：【xxxxxxx】（若不是因为修复问题而新增该类，则留空）
 * 开发人员：qiuyf
 * 创建日期：2019年4月17日 下午2:14:34
 * 功能描述：个人用信申请查询接口
 */
@RestController
@RequestMapping("/esb")
public class PersonLetterApplyController extends AbstractController {

	private static Logger logger = LoggerFactory.getLogger(PersonLetterApplyController.class);

	private static int total = 0;

	@ModelAttribute("esbReqServiceBean")
	public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
		logger.info("获取ESB请求对象，校验 ESB请求系统头和请求应用头对象开始");
		EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
		return esbReqServiceBean;
	}

	@ModelAttribute("reqPersonLetterAppBean")
	public ReqPersonLetterAppBean getReqEsbBodyBean(HttpServletRequest request) {
		logger.info("获取个人用信申请查询接口请求对象，校验个人用信申请查询接口请求体对象开始");
		String esbReqBody = (String) request.getAttribute("esbReqBody");
		return JSONObject.parseObject(esbReqBody, ReqPersonLetterAppBean.class);
	}

	@PostMapping("/SERVICE_30230001_02")
	public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqPersonLetterAppBean") ReqPersonLetterAppBean reqPersonLetterAppBean, BindingResult br2, Exception exception) {
		String qryType = reqPersonLetterAppBean.getQryTp();
		String globalSerno = esbReqServiceBean.getSysHead().getGlblSrlNo();
		TraceUtil.setTraceId(globalSerno);
		logger.info("个人用信申请查询接口处理开始----------查询类型是："+LetterQueryType.getValue(qryType));
		List<NlsApplyInfoVO> result = new ArrayList<NlsApplyInfoVO>();
		try {
			// 通过切面校验个人用信申请查询请求参数是否正确，如不正确则返回错误信息
			if (Objects.nonNull(exception)) {
				throw exception;
			}
			// 个人用信申请查询
			result = this.letterApplyQueryDeal(reqPersonLetterAppBean);

			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
					JSONObject.toJSONString(buildRespPersonLetterAppBean(result, EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), LetterQueryType.getValue(qryType)+"完成",
							reqPersonLetterAppBean)),
					EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), LetterQueryType.getValue(qryType)+"完成");

		} catch (BizException e) {
			logger.error("***********调用个人用信申请查询接口处理失败**************"+e.getMessage());
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
					JSONObject.toJSONString(buildRespPersonLetterAppBean(result, e.getErrorCode(), e.getMessage(), reqPersonLetterAppBean)),
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), e.getErrorCode(), e.getMessage());
		}
		catch (Exception e) {
			logger.error("***********调用个人用信申请查询接口处理失败**************"+e.getMessage());
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
					JSONObject.toJSONString(buildRespPersonLetterAppBean(result, EsbRetCodeStandard.OTHERS_EXCEPTION.getValue(), e.getMessage(), reqPersonLetterAppBean)),
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbRetCodeStandard.OTHERS_EXCEPTION.getValue(), e.getMessage());
		} finally {
			logger.info("个人用信申请查询接口处理结束----------");
			TraceUtil.clear();
		}

	}

	//个人用信申请查询逻辑处理
	private List<NlsApplyInfoVO> letterApplyQueryDeal(ReqPersonLetterAppBean reqPersonLetterAppBean) throws Exception {
		List<NlsApplyInfoVO> result = new ArrayList<NlsApplyInfoVO>();
		Integer pageSize = 0;
		Integer startNum = 0;
		String qryType = reqPersonLetterAppBean.getQryTp();
		if(!LetterQueryType.ONE_LETTER.getKey().equals(qryType)) {
			String pageNo = reqPersonLetterAppBean.getPgNo();
			String tempPageSize = reqPersonLetterAppBean.getPerPgRcrNum();
			//页码、每页显示条数均不为空
			if(StringUtil.isStrNotEmpty(pageNo) && StringUtil.isStrNotEmpty(tempPageSize)) {
				if(StringUtil.isStrNotEmpty(pageNo) && StringUtil.isStrNotEmpty(tempPageSize)) {
					pageSize = Integer.valueOf(tempPageSize);
					if(Integer.valueOf(pageNo) > 1){
						startNum = Math.abs((Integer.valueOf(pageNo) - 1)) * pageSize;
					}
				}
			}
			//页码、每页显示条数均为空
			else if(StringUtil.isNullorBank(pageNo) && StringUtil.isNullorBank(tempPageSize)) { }
			else {
				throw new Exception(LetterQueryType.getValue(qryType) + "失败，请明确是否需要分页查询，并输入正确的参数！");
			}
		}
		/* 单笔用信信息查询 */
		if(LetterQueryType.ONE_LETTER.getKey().equals(qryType)) {
			String applySeq = reqPersonLetterAppBean.getUseCrdtAppFlowNo();
			if(StringUtil.isNullorBank(applySeq)) {
				throw new BizException(EsbRetCodeStandard.JKYDCSJYBTG.getValue(), "单笔用信信息查询，必输输入用信申请流水号，请核查！");
			}
			NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO();
			nlsApplyInfoVO.setApplySeq(applySeq);
			nlsApplyInfoVO = nlsApplyInfoService.queryByPk(nlsApplyInfoVO);
			if(Objects.nonNull(nlsApplyInfoVO)) {
				result.add(nlsApplyInfoVO);
				total = 1;
			}
		}
		else if(LetterQueryType.ONE_LIMIT_ALL.getKey().equals(qryType) || LetterQueryType.ONE_LIMIT_APPR_ALL.getKey().equals(qryType)) {
			String lmtApplySeq = reqPersonLetterAppBean.getCrdtAppFlowNo();
			if(StringUtil.isNullorBank(lmtApplySeq)) {
				throw new BizException(EsbRetCodeStandard.JKYDCSJYBTG.getValue(), LetterQueryType.getValue(qryType) + "，必输输入授信申请流水号，请核查！");
			}else {
				/* 单笔额度下所有的用信申请信息查询 */
				if(LetterQueryType.ONE_LIMIT_ALL.getKey().equals(qryType)) {
					NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO(lmtApplySeq, null, null, null, null, null, startNum, pageSize);
					result = nlsApplyInfoService.qryListByConditionsTwo(nlsApplyInfoVO);

					this.isQueryTotal(result, nlsApplyInfoVO);
				}
				/* 单笔额度下所有处理中、通过、拒绝的用信申请信息查询  */
				else {
					String apprvSts = reqPersonLetterAppBean.getAprvSt();
					if(StringUtil.isNullorBank(apprvSts)) {
						throw new BizException(EsbRetCodeStandard.JKYDCSJYBTG.getValue(), LetterQueryType.getValue(qryType) + "，授信申请流水号、审批状态必输，请核查！");
					}else {
						NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO(lmtApplySeq, null, null, apprvSts, null, null, startNum, pageSize);
						result = nlsApplyInfoService.qryListByConditionsTwo(nlsApplyInfoVO);

						this.isQueryTotal(result, nlsApplyInfoVO);
					}
				}
			}
		} // end of 2、3，授信申请流水号
		else {
			String certCode = reqPersonLetterAppBean.getCertNo();
			String certType = reqPersonLetterAppBean.getCertTp();
			if(StringUtil.isNullorBank(certCode)) {
				throw new BizException(EsbRetCodeStandard.KHXXJYBTG.getValue(), LetterQueryType.getValue(qryType) + "，证件号码必输，请核查！");
			}
			if(StringUtil.isNullorBank(certType)) {
				throw new BizException(EsbRetCodeStandard.KHXXJYBTG.getValue(), LetterQueryType.getValue(qryType) + "，证件类型必输，请核查！");
			}
			/* 单客户下所有的用信申请信息查询 */
			if(LetterQueryType.ONE_CUS_ALL.getKey().equals(qryType)) {
				NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO(null, certType, certCode, null, null, null, startNum, pageSize);
				result = nlsApplyInfoService.qryListByConditionsTwo(nlsApplyInfoVO);

				this.isQueryTotal(result, nlsApplyInfoVO);
			}
			/* 单客户下某个产品下所有的用信申请信息查询 */
			else if(LetterQueryType.ONE_CUS_PRDID_ALL.getKey().equals(qryType)) {
				String prdId = reqPersonLetterAppBean.getPrdctID();
				if(StringUtil.isNullorBank(prdId)) {
					throw new BizException(EsbRetCodeStandard.JKYDCSJYBTG.getValue(), LetterQueryType.getValue(qryType) + "，证件类型、证件号码、产品ID必输，请核查！");
				}else {
					NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO(null, certType, certCode, null, prdId, null, startNum, pageSize);
					result = nlsApplyInfoService.qryListByConditionsTwo(nlsApplyInfoVO);

					this.isQueryTotal(result, nlsApplyInfoVO);
				}
			}
			/* 单客户下某个渠道下所有的用信申请信息查询 */
			else if(LetterQueryType.ONE_CUS_CHANNEL_ALL.getKey().equals(qryType)) {
				String channelNo = reqPersonLetterAppBean.getChanNo();
				if(StringUtil.isNullorBank(channelNo)) {
					throw new BizException(EsbRetCodeStandard.JKYDCSJYBTG.getValue(), LetterQueryType.getValue(qryType) + "，证件类型、证件号码、渠道编号必输，请核查！");
				}else {
					NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO(null, certType, certCode, null, null, channelNo, startNum, pageSize);
					result = nlsApplyInfoService.qryListByConditionsTwo(nlsApplyInfoVO);

					this.isQueryTotal(result, nlsApplyInfoVO);
				}
			}
			/* 单客户下查询所有处理中、通过、拒绝的用信申请信息查询 */
			else {
				String apprSts = reqPersonLetterAppBean.getAprvSt();
				if(StringUtil.isNullorBank(apprSts)) {
					throw new BizException(EsbRetCodeStandard.JKYDCSJYBTG.getValue(), LetterQueryType.getValue(qryType) + "，证件类型、证件号码、审批状态必输，请核查！");
				}else {
					NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO(null, certType, certCode, apprSts, null, null, startNum, pageSize);
					result = nlsApplyInfoService.qryListByConditionsTwo(nlsApplyInfoVO);

					this.isQueryTotal(result, nlsApplyInfoVO);
				}
			}
		} // end of 4、5、6、7，证件号码，证件类型
		return result;
	}

	//个人用信信息查询响应Bean组装
	private static RespPersonLetterAppBean buildRespPersonLetterAppBean(List<NlsApplyInfoVO> result, String retCode, String rtnMsg, ReqPersonLetterAppBean reqPersonLetterAppBean) {
		logger.debug("*********组装个人用信申请查询接口响应bean开始 .... *********");
		String cusId = reqPersonLetterAppBean.getClntNo();
		String cusName = "";
		String certType = reqPersonLetterAppBean.getCertTp();
		String certCode = reqPersonLetterAppBean.getCertNo();
		RespPersonLetterAppBean respPersonLetterAppBean = new RespPersonLetterAppBean();
		respPersonLetterAppBean.setRetCd(retCode);
		respPersonLetterAppBean.setRetMsg(rtnMsg);
		respPersonLetterAppBean.setPgNo(reqPersonLetterAppBean.getPgNo());
		respPersonLetterAppBean.setPerPgRcrNum(reqPersonLetterAppBean.getPerPgRcrNum());
		if(null==result || result.isEmpty()) {
			respPersonLetterAppBean.setCrrspnQryTotCnt("0");
		}else {
			List<RespNlsApplArr> tempList = new ArrayList<>();
			Iterator<NlsApplyInfoVO> iterator = result.iterator();
			while(iterator.hasNext()) {
				NlsApplyInfoVO temp = iterator.next();
				RespNlsApplArr respNlsApplArr = new RespNlsApplArr();
				/* 用信申请流水号 （原交易流水号） */
				respNlsApplArr.setUseCrdtAppFlowNo(temp.getApplySeq());
				/* 授信申请流水号 */
				respNlsApplArr.setCrdtAppFlowNo(temp.getLmtApplySeq());
				/* 申请日期 */
				respNlsApplArr.setAplDt(temp.getApplyDate());
				/* 申请时间  */
				respNlsApplArr.setAppTm(temp.getApplyTime());
				/* 申请金额 */
				respNlsApplArr.setAppAmt(null == temp.getApplyAmt() ? BigDecimal.ZERO.toString() : temp.getApplyAmt().toString());
				/* 审批状态 */
				respNlsApplArr.setAprvSt(temp.getNlsApplyState());
				/* 拒绝原因 */
				respNlsApplArr.setRfsRsn(temp.getRefuseCause());
				/* 贷款期限*/
				respNlsApplArr.setLoanTrm(temp.getLoanTerm());
				/* 贷款用途 */
				respNlsApplArr.setLoanUsg(temp.getLoanPurpose());
				/* 产品代码 */
				respNlsApplArr.setProdCd(temp.getPrdCode());
				/* 产品名称 */
				respNlsApplArr.setLoanProdNm(temp.getPrdName());
				/* 执行利率  */
				respNlsApplArr.setExecRate(null == temp.getLoanRate() ? BigDecimal.ZERO.toString() : temp.getLoanRate().toString());
				/* 放款状态 */
				respNlsApplArr.setLoanSt(temp.getDnSts());
				/* 放款金额 */
				respNlsApplArr.setDistrAmt(temp.getAmountOfLoan());
				/* 渠道编号 */
				respNlsApplArr.setChanNo(temp.getChannelNo());
				try {
					/* 期限类型  */
					respNlsApplArr.setLoanTrmType(SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_IFP, SDicToExternalConstant.TERM_TYPE, temp.getLoanTermType()));
					/* 币种 */
					respNlsApplArr.setCcy(SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_IFP, SDicToExternalConstant.CUR_TYPE, temp.getLoanCcy()));
					/* 还款方式  */
					respNlsApplArr.setRpyMd(SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_IFP, SDicToExternalConstant.REPAY_MODE, temp.getRepayMethod()));
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("字典项转换出错，错误信息为：", e);
				}
				cusId = StringUtil.isStrNotEmpty(temp.getCusId()) ? temp.getCusId() : cusId;
				cusName = StringUtil.isStrNotEmpty(temp.getCusName()) ? temp.getCusName() : cusName;
				certType = StringUtil.isStrNotEmpty(temp.getCertType()) ? temp.getCertType() : certType;
				certCode = StringUtil.isStrNotEmpty(temp.getCertCode()) ? temp.getCertCode() : certCode;

				tempList.add(respNlsApplArr);
			}
			/* 客户号 */
			respPersonLetterAppBean.setClntNo(cusId);
			/* 客户姓名*/
			respPersonLetterAppBean.setCustNm(cusName);
			/* 证件类型*/
			respPersonLetterAppBean.setCertTp(certType);
			/* 证件号码 */
			respPersonLetterAppBean.setCertNo(certCode);

			respPersonLetterAppBean.setCrrspnQryTotCnt(String.valueOf(total));
			respPersonLetterAppBean.setDistrInfArry(tempList);
		}
		logger.debug("*********组装个人用信申请查询接口响应bean结束！" + ",返回码:" + retCode + ",返回信息:" + rtnMsg + "**********");
		return respPersonLetterAppBean;
	}

	private void isQueryTotal(List<NlsApplyInfoVO> result, NlsApplyInfoVO nlsApplyInfoVo) {
		if(null != result && !result.isEmpty()) {
			total = nlsApplyInfoService.queryTotalByCondition(nlsApplyInfoVo);
		}
	}
	@Autowired
	@Qualifier("nlsApplyInfoService")
	private NlsApplyInfoService nlsApplyInfoService;

}
